package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"video-social/cache"
	"video-social/model"
	"video-social/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	redis_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}

	var user model.User
	err := model.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)

		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次，封禁2个小时",
			})
			return
		}

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": pkg.Md5Str(password),
	})
	return

}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))

	offset := (page - 1) * size

	var video []model.Video

	redis_key := "video_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&video)
		jsonData, _ := json.Marshal(video)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &video)
	}

	var count int64
	model.DB.Model(model.Video{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  video,
		"count": count,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")

	var video model.Video
	redis_key := "video_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id = ?", id).First(&video)
		jsonData, _ := json.Marshal(video)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(cacheData), &video)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": video,
	})
	return
}
func Like(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Query("user_id"))
	videoId, _ := strconv.Atoi(c.Query("video_id"))

	like := model.Like{
		UserID:  userId,
		VideoID: videoId,
	}
	tx := model.DB.Begin()
	err := tx.Create(&like).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞记录添加失败",
		})
		return
	}

	var video model.Video
	err = tx.Where("id = ?", videoId).First(&video).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞记录不存在",
		})
		return
	}

	video.LikeCount++
	err = tx.Save(&video).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "点赞记录更新失败",
		})
		return
	}
	tx.Commit()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "点赞成功",
	})
	return

}
